package com.ty.controller;

import com.ty.bean.BootStrapResultData;
import com.ty.bean.BootStrapTableExpress;
import com.ty.bean.Express;
import com.ty.bean.Message;
import com.ty.mvc.ResponseBody;
import com.ty.service.BaseExpressService;
import com.ty.service.impl.BaseExpressServiceImpl;
import com.ty.util.DateFormatUtil;
import com.ty.util.JSONUtil;
import com.ty.util.UserUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author 田野
 */
public class ExpressController {
    BaseExpressService service = new BaseExpressServiceImpl();
    @ResponseBody("/express/console.do")
    public String console(HttpServletRequest request, HttpServletResponse response){
        List<Map<String, Integer>> data = service.console();
        Integer total = data.get(0).get("data1_size");
        // 利用session存储快递总数，并在删除和添加的时候进行变化
        HttpSession session = request.getSession();
        session.setAttribute("totalExpresses", total);

        Message message = null;
        if (data != null && data.size() > 0){
            message = new Message();
            message.setStatus(0);
        }else {
            message.setStatus(-1);
        }
        message.setData(data);
        String json = JSONUtil.toJSON(message);
        System.out.println(json);
        // 给前端发送数据
        // 只需要return 出去，就会自动响应前台发送的请求。
        // 等价于response.getWriter().write(json);
        // 或者是response.getWriter().print(json);
        return json;
    }

    @ResponseBody("/express/list.do")
    public String list(HttpServletRequest request, HttpServletResponse response){
        // 1、获取参数（前台发过来的数据，例如现在是第几页，一共需要多少个数据等）
        // 获取查询数据的起始索引值
        String offset = request.getParameter("offset");
        // 获取当前页要显示的数据量
        String pageNumber = request.getParameter("pageNumber");
        List<BootStrapTableExpress> list2 = new ArrayList<>();
        // 2、调用Service层方法
        if (offset != null && pageNumber != null){
            List<Express> list = service.findAll(true, Integer.parseInt(offset), Integer.parseInt(pageNumber));
            for (Express express : list) {
                BootStrapTableExpress bootStrapTableExpress = new BootStrapTableExpress();
                bootStrapTableExpress.setId(express.getId());
                bootStrapTableExpress.setNumber(express.getNumber());
                bootStrapTableExpress.setUsername(express.getUsername());
                bootStrapTableExpress.setUserPhone(express.getUserPhone());
                bootStrapTableExpress.setCompany(express.getCompany());

                if (express.getCode() != null){
                    bootStrapTableExpress.setCode(express.getCode());
                }else {
                    bootStrapTableExpress.setCode("已取件");
                }
                // 日期工具类进行日期格式化
                bootStrapTableExpress.setInTime(DateFormatUtil.format(express.getInTime()));
                if (express.getOutTime() != null){
                    bootStrapTableExpress.setOutTime(DateFormatUtil.format(express.getOutTime()));
                }else {
                    bootStrapTableExpress.setOutTime("待取件");
                }
                bootStrapTableExpress.setSysPhone(express.getSysPhone());
                Integer status = express.getStatus();
                if (status == 0){
                    bootStrapTableExpress.setStatus("待取");
                }else if (status == 1){
                    bootStrapTableExpress.setStatus("已取");
                }else {
                    bootStrapTableExpress.setStatus("" + express.getStatus());
                }
                list2.add(bootStrapTableExpress);
            }

            // 其实后面可以优化这个部分，利用session缓存等等或者一些算法，不需要再去查询一遍数据库
            // TODO:取session值
            HttpSession session = request.getSession();
            Integer total = (Integer) session.getAttribute("totalExpresses");

            // 3、将结果进行封装（即让bootstrap能够识别的数据类型）
            BootStrapResultData<BootStrapTableExpress> data = new BootStrapResultData<>();
            data.setRows(list2);
            data.setTotal(total);

            String json = JSONUtil.toJSON(data);
            return json;
        }
        return null;
    }
    @ResponseBody("/express/insert.do")
    public String insert(HttpServletRequest request, HttpServletResponse response){
        // 1、接收参数
        String number = request.getParameter("number");
        String company = request.getParameter("company");
        String username = request.getParameter("username");
        String userPhone = request.getParameter("userPhone");
        // 2、调用Service层方法
        Express express = new Express();
        express.setNumber(number);
        express.setUsername(username);
        express.setUserPhone(userPhone);
        express.setCompany(company);

        // TODO:还没有编写柜子端，未存储任何的录入人的信息，先固定的设置一个sysPhone，后期再改
        express.setSysPhone(UserUtil.getUserPhone(request.getSession()));

        boolean insert = service.insert(express);
        Message message = new Message();
        // 3、返回结果给Servlet，然后由Servlet将结果返回给前端进行展示
        if (insert){
            // 更新session值
            HttpSession session = request.getSession();
            Integer totalExpresses = (Integer) session.getAttribute("totalExpresses");
            session.setAttribute("totalExpresses", totalExpresses + 1);

            message.setStatus(0);
            message.setResult("快递录入成功！");
        }else {
            message.setStatus(-1);
            message.setResult("快递录入失败！");
        }
        String json = JSONUtil.toJSON(message);
        return json;

    }
    @ResponseBody("/express/insertCheckByNumber.do")
    public String insertCheckByNumber(HttpServletRequest request, HttpServletResponse response){
        // 1、获取参数
        String number = request.getParameter("checkNumber");
        System.out.println("checkNumber:" + number);
        // 2、调用Service层方法
        Express byNumber = service.findByNumber(number);
        // 3、返回封装的信息给Servlet
        Message message = new Message();
        if (byNumber != null){
            message.setStatus(-1);
            message.setResult("单号重复，请重新录入！");
            message.setData(number);
        }else {
            message.setStatus(0);
        }
        String json = JSONUtil.toJSON(message);
        System.out.println(json);
        return json;
    }
    @ResponseBody("/express/find.do")
    public String find(HttpServletRequest request, HttpServletResponse response){
        String number = request.getParameter("number");
        Express byNumber = service.findByNumber(number);
        Message message = new Message();
        if (byNumber != null){
            // 此单号的快递存在
            message.setStatus(0);
            message.setResult("查询成功");
            message.setData(byNumber);
        }else {
            // 此单号的快递不存在
            message.setStatus(-1);
            message.setResult("快递不存在！");
        }
        String json = JSONUtil.toJSON(message);
        return json;
    }
    @ResponseBody("/express/update.do")
    public String update(HttpServletRequest request, HttpServletResponse response){
        String expressId = request.getParameter("expressId");
        String editNumber = request.getParameter("editNumber");
        String editCompany = request.getParameter("editCompany");
        String editUsername = request.getParameter("editUsername");
        String editUserPhone = request.getParameter("editUserPhone");
        String status = request.getParameter("status");

        // 封装对象
        Express express = new Express();

        express.setId(Integer.parseInt(expressId));
        express.setNumber(editNumber);
        express.setCompany(editCompany);
        express.setUsername(editUsername);
        // 这里要注意
        express.setUserPhone(editUserPhone);
        express.setStatus(Integer.parseInt(status));

        // TODO:还没有编写柜子端，未存储任何的录入人的信息，先固定的设置一个sysPhone，后期再改
        express.setSysPhone(UserUtil.getUserPhone(request.getSession()));

        boolean update = service.update(Integer.parseInt(expressId), express);
        Message message = new Message();
        if (update){
            // 修改成功
            message.setStatus(0);
            message.setResult("修改成功！");
        }else {
            // 修改失败
            message.setStatus(-1);
            message.setResult("修改失败！");
        }

        String json = JSONUtil.toJSON(message);

        return json;

    }

    @ResponseBody("/express/delete.do")
    public String delete(HttpServletRequest request, HttpServletResponse response){
        String expressId = request.getParameter("expressId");

        boolean delete = service.delete(Integer.parseInt(expressId));

        Message message = new Message();

        if (delete){
            // 更新session值
            HttpSession session = request.getSession();
            Integer totalExpresses = (Integer) session.getAttribute("totalExpresses");
            session.setAttribute("totalExpresses", totalExpresses - 1);
            message.setStatus(0);
            message.setResult("删除成功！");
        }else {
            message.setStatus(-1);
            message.setResult("删除失败！");
        }

        String json = JSONUtil.toJSON(message);

        return json;

    }



}
